//
//  ReadListInfoViewController.m
//  Leisure
//
//  Created by 大展 on 16/6/30.
//  Copyright © 2016年 大展. All rights reserved.
//

#import "ReadListInfoViewController.h"

@interface ReadListInfoViewController ()<UITableViewDelegate,UITableViewDataSource, UIWebViewDelegate>

@property (nonatomic, strong)UIWebView *webView;
@property (nonatomic, strong)NSString *html;
@property (nonatomic, strong)UITableView *tableView; // 评论列表
@property (nonatomic, strong)NSMutableArray *commentArray; // 评论数组
@property (nonatomic, strong)CommentView *commentView; // 评论视图

@end

@implementation ReadListInfoViewController

- (CommentView *)commentView {

    if (!_commentView) {

        // 从xib中获取view
        _commentView = [[NSBundle mainBundle]loadNibNamed:@"CommentView" owner:nil options:nil].lastObject;
        _commentView.frame = CGRectMake(0, kHeight-50, kWidth, 50);
    }
    return _commentView;
}

- (NSMutableArray *)commentArray {

    if (!_commentArray) {

        _commentArray = [NSMutableArray array];
    }
    return _commentArray;
}

- (UITableView *)tableView {

    if (!_tableView) {

        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kWidth, kHeight-64-50) style:(UITableViewStylePlain)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (UIWebView *)webView {

    if (!_webView) {

        _webView = [[UIWebView alloc]initWithFrame:self.view.frame];
        _webView.delegate = self;
        _webView.scrollView.bounces = NO;
        _webView.scrollView.bouncesZoom = NO;
        _webView.userInteractionEnabled = NO;
    }
    return _webView;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];


    // 请求数据
    [RequestManager fecthDataWithUrl:KReadListInfoUrl parameter:@{@"contentid":self.readListModel.ID} mehtod:@"POST" compelet:^(NSData *data) {

        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",bigDic);
        // 根据<pre>进行切割
        NSArray *array = [bigDic[@"data"][@"html"]  componentsSeparatedByString:@"<pre>"];
        [self.webView loadHTMLString:array[0] baseURL:nil];
        self.html = array[0];

    } updateUI:^{

    }];

    // 添加评论事件
    [self.commentView.sendBtn addTarget:self action:@selector(sendCommentAction) forControlEvents:UIControlEventTouchUpInside];
}

// 获取评论
- (void)fetchCommentWith:(void(^)())block {

    // 评论请求
    [RequestManager fecthDataWithUrl:kCommentUrl parameter:@{@"contentid":self.readListModel.ID} mehtod:@"POST" compelet:^(NSData *data) {


        NSDictionary *bigDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//        NSLog(@"%@",bigDic);
        for (NSDictionary *smallDic in bigDic[@"data"][@"list"]) {

            [self.commentArray addObject:smallDic[@"content"]];
        }
    } updateUI:^{

        [self.tableView reloadData];
//        if (block) {
//
//            block();
//        }
    }];
}

//评论事件
- (void)sendCommentAction {


    [RequestManager fecthDataWithUrl:kSendCommentUrl parameter:@{@"auth":@"CcJvRS7m1m3m35DCsh1HMTtlzJxQcT4MuSK8jttDGYm3cWP22tJJShlV7m3s",@"contentid":self.readListModel.ID,@"content":self.commentView.textFiled.text} mehtod:@"POST" compelet:^(NSData *data) {

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",dic);
    } updateUI:^{

        // 清空原数组中的数据
        [self.commentArray removeAllObjects];
        [self fetchCommentWith:^{

            if (self.commentArray.count > 0) {

                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.commentArray.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
            }
        }];
    }];
}

// 收藏事件
- (void)itemAction {

    [[CoreDataManager defaultManager] insertCollectionModelWithReadModel:self.readListModel html:self.html];
}

#pragma mark -----webViewDelegate-----
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString *js = @"function imgAutoFit() { \
    var imgs = document.getElementsByTagName('img'); \
    for (var i = 0; i < imgs.length; ++i) {\
    var img = imgs[i];   \
    img.style.maxWidth = %f;   \
    } \
    }";
    js = [NSString stringWithFormat:js, [UIScreen mainScreen].bounds.size.width - 20];

    [webView stringByEvaluatingJavaScriptFromString:js];
    [webView stringByEvaluatingJavaScriptFromString:@"imgAutoFit()"];

    self.navigationItem.rightBarButtonItem = ({

        UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithTitle:@"收藏" style:(UIBarButtonItemStylePlain) target:self action:@selector(itemAction)];
        item;
    });

    // 请求评论
    [self fetchCommentWith:NULL];

    CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight;"] floatValue];
    NSLog(@"%f",height);

    // 改变webView的Frame
    CGRect webViewFrame = webView.frame;
    webViewFrame.size.height = height+10;
    webView.frame = webViewFrame;

    self.tableView.tableHeaderView = webView;
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.commentView];
}

- (void)webViewDidStartLoad:(UIWebView *)webView {

    NSLog(@"开始加载");

}

#pragma mark TableViewDelegate 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.commentArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cell"];

    cell.textLabel.text = self.commentArray[indexPath.row];

    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
